package com.thexb.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.thexb.sys.entity.Role;
import com.thexb.sys.entity.RoleMenu;
import com.thexb.sys.mapper.RoleMapper;
import com.thexb.sys.service.IRoleMenuService;
import com.thexb.sys.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author thexb
 * @since 2023-04-04
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private IRoleMenuService iRoleMenuService;

    @Override
    @Transactional
    public void addRole(Role role) {
        this.save(role);
        Integer[] menuIds = role.getMenuIds();
        for (Integer menuId : menuIds) {
            iRoleMenuService.save(new RoleMenu(null, role.getRoleId(), menuId));
        }
    }

    @Override
    public Role getRoleById(int id) {
        Role role = this.getById(id);
        Integer[] menuIdsByRoleId = this.baseMapper.getMenuIdsByRoleId(id);
        role.setMenuIds(menuIdsByRoleId);
        return role;
    }

    @Override
    @Transactional
    public void updateRole(Role role) {
        // 更新角色
        this.baseMapper.updateById(role);
        // 删除以前的权限
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRoleId, role.getRoleId());
        iRoleMenuService.remove(wrapper);
        // 添加新权限
        Integer[] menuIds = role.getMenuIds();
        for (Integer menuId : menuIds) {
            iRoleMenuService.save(new RoleMenu(null, role.getRoleId(), menuId));
        }
    }

    @Override
    @Transactional
    public void removeRole(int id) {
        // 更新角色
        this.removeById(id);
        // 删除以前的权限
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRoleId, id);
        iRoleMenuService.remove(wrapper);
    }
}
